package com.zzc.config;

import com.zzc.pojo.UserInfor;
import com.zzc.service.UserServiceImp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImp userServiceImp;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录用户
        Subject subject =  SecurityUtils.getSubject();
        //拿到userinfor对象
        UserInfor userInfor = (UserInfor) subject.getPrincipal();
        //设置权限
        info.addStringPermission(userInfor.getPerms());
//        info.addRole();
        return info;
    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取当前登录的用户
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        UserInfor userInfor = userServiceImp.queryUserByName(userToken.getUsername());
        if (userInfor==null){
            return null;  //自动抛出异常 UnknownAccountException
        }
        //自动验证密码
        return new SimpleAuthenticationInfo(userInfor,userInfor.getUserpassword(),"");
    }
}
